package com.scs.application.modules.fsd.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.utils.DateUtils;
import com.scs.application.core.utils.PinYinUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.fsd.consts.FsdConst;
import com.scs.application.modules.fsd.dto.SaveStockDTO;
import com.scs.application.modules.fsd.entity.*;
import com.scs.application.modules.fsd.mapper.IntelliAPIMapper;
import com.scs.application.modules.fsd.mapper.NJGLMapper;
import com.scs.application.modules.fsd.service.*;
import com.scs.application.modules.fsd.thirdparty.properties.gulou.HaiYuSOAP;
import com.scs.application.modules.fsd.vo.*;
import com.scs.application.modules.sys.security.UserPrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 */
@Service
public class NJGLServiceImpl extends SPDServiceImpl implements NJGLService {
    @Autowired
    private FsdStockService fsdStockService;
    @Autowired
    private RecordService recordService;
    @Autowired
    private FsdUserService fsdUserService;
    @Autowired
    private FsdRoleService fsdRoleService;
    @Autowired
    private IntelliAPIMapper intelliAPIMapper;
    @Autowired
    private FsdCallInterfaceService fsdCallInterfaceService;
    @Autowired
    private NJGLMapper njglMapper;

    @Override
    public Object getOutboundOrder(String stationCode) {
        String sql = "select DISTINCT WO_KEY from VIEW_SPD_WO where WAREHOUSE_CODE_TO ='" + stationCode + "' and  OP_FLAG = 'DOWN'  ORDER BY WO_KEY";//";//RFID in (select rfid from VIEW_SPD_STOCK_MAIN ) and ROWNUM <=2
        List<DeliveryOrderResult> orderResults = new ArrayList<>();
        try {
            ResultSet rs = executeQueryBySql(sql);
            while (rs.next()) {
                DeliveryOrderResult deliveryOrderResult = new DeliveryOrderResult();
                deliveryOrderResult.setOrderId(rs.getString("WO_KEY"));
//                deliveryOrderResult.setStorageCode(rs.getString("WAREHOUSE_CODE_TO"));
//                deliveryOrderResult.setMaterialName(rs.getString("MATR_NAME"));
//                deliveryOrderResult.setRfid(rs.getString("rfid"));
                orderResults.add(deliveryOrderResult);
            }
        } catch (Exception e) {
            return e.getMessage();
        }
        return orderResults;
    }

    @Override
    public Object getOrderDet(List<String> orderId) {
        String sql = "select * from VIEW_SPD_WO where WO_KEY in ('" + String.join("','", orderId) + "') ORDER BY WO_KEY ";
        List<DeliveryOrderResult> orderResults = new ArrayList<>();
        try {
            ResultSet rs = executeQueryBySql(sql);
            while (rs.next()) {
                DeliveryOrderResult deliveryOrderResult = new DeliveryOrderResult();
                deliveryOrderResult.setStorageCode(rs.getString("WAREHOUSE_CODE_TO"));
                deliveryOrderResult.setOrderId(rs.getString("WO_KEY"));
                deliveryOrderResult.setMaterialName(rs.getString("MATR_NAME"));
                deliveryOrderResult.setPy(PinYinUtils.getAlpha(rs.getString("MATR_NAME")) + rs.getString("WO_KEY") + rs.getString("rfid"));
                deliveryOrderResult.setRfid(rs.getString("rfid"));
                deliveryOrderResult.setAmount(0);
                List<Map<String, String>> desc = new ArrayList<>();
                Map<String, String> item = new HashMap<>();
                item.put("label", "品名");
                item.put("value", rs.getString("MATR_NAME"));
                desc.add(item);
                item = new HashMap<>();
                item.put("label", "单号");
                item.put("value", rs.getString("WO_KEY"));
                desc.add(item);
                item = new HashMap<>();
                item.put("label", "rfid");
                item.put("value", rs.getString("rfid"));
                desc.add(item);
                deliveryOrderResult.setDesc(desc);
                orderResults.add(deliveryOrderResult);
            }
        } catch (Exception e) {
            return e.getMessage();
        }
        return orderResults;
    }

    @Override
    public Object getOrderItem(List<String> orderId) {
        String sql = "select WO_KEY,GOODS_OPCODE,MATR_NAME,MATR_SPEC,WAREHOUSE_CODE_FROM,WAREHOUSE_CODE_TO,PACKAGE_QTY,LOT,EXP_DATE,RFID,OP_FLAG from VIEW_SPD_WO where WO_KEY in ('" + String.join("','", orderId) + "')  ORDER BY WO_KEY ";
        List<ViewWo> orderResults = new ArrayList<>();
        Map<String, Object> orderList = new HashMap<>();
        try {
            ResultSet rs = executeQueryBySql(sql);
            while (rs.next()) {
                ViewWo viewWo = new ViewWo();
                viewWo.setWO_KEY(rs.getString("WO_KEY"));
                viewWo.setGOODS_OPCODE(rs.getString("GOODS_OPCODE"));
                viewWo.setMATR_NAME(rs.getString("MATR_NAME"));
                viewWo.setMATR_SPEC(rs.getString("MATR_SPEC"));
                viewWo.setWAREHOUSE_CODE_FROM(rs.getString("WAREHOUSE_CODE_FROM"));
                viewWo.setWAREHOUSE_CODE_TO(rs.getString("WAREHOUSE_CODE_TO"));
                viewWo.setPACKAGE_QTY(rs.getString("PACKAGE_QTY"));
                viewWo.setLOT(rs.getString("LOT"));
                viewWo.setEXP_DATE(rs.getString("EXP_DATE"));
                viewWo.setRFID(rs.getString("RFID"));
                viewWo.setOP_FLAG(rs.getString("OP_FLAG"));
                orderResults.add(viewWo);
            }
            for (String id : orderId) {
                orderList.put(id, orderResults.stream().filter((ViewWo w) -> w.getWO_KEY().equals(id)).collect(Collectors.toList()));
            }
        } catch (Exception e) {
            return e.getMessage();
        }
        return orderList;
    }

    @Override
    public Object getTheoryStock(String stationCode) {
        String sql = "select GOODS_OPCODE,MATR_NAME,MATR_SPEC,MATR_UNIT,WAREHOUSE_CODE,PACKAGE_QTY,LOT,EXP_DATE,RFID from VIEW_SPD_STOCK_MAIN where WAREHOUSE_CODE = '" + stationCode + "'";
        List<ViewStock> orderResults = new ArrayList<>();
        try {
            ResultSet rs = executeQueryBySql(sql);
            while (rs.next()) {
                ViewStock viewStock = new ViewStock();
                viewStock.setGoods_opcode(rs.getString("GOODS_OPCODE"));
                viewStock.setMatr_name(rs.getString("MATR_NAME"));
                viewStock.setMatr_spec(rs.getString("MATR_SPEC"));
                viewStock.setMatr_unit(rs.getString("MATR_UNIT"));
                viewStock.setWarehouse_code(rs.getString("WAREHOUSE_CODE"));
                viewStock.setPackage_qty(rs.getString("PACKAGE_QTY"));
                viewStock.setLot(rs.getString("LOT"));
                viewStock.setExp_date(rs.getString("EXP_DATE"));
                viewStock.setRfid(rs.getString("RFID"));
                orderResults.add(viewStock);
            }
        } catch (Exception e) {
            return e.getMessage();
        }
        return orderResults;
    }

    @Override
    public Object getScanResult(String stationCode, String business, List<SaveStockDTO> stockList) {
        // 获取扫描到的rfid集合
        List<String> actualRfids = stockList.stream().map(SaveStockDTO::getRfid).collect(Collectors.toList());
        String changeTime = DateUtils.nowDate();
        if (business.equals("OutboundOrder") || business.equals("Delivery"))
            //保存业务界面的扫描记录
            recordService.saveRecord(stationCode, changeTime, business.equals("OutboundOrder") ? 1 : 0, actualRfids);
        Map<String, Object> del = new HashMap<>();
        String sql = "select WAREHOUSE_CODE,MATR_NAME,rfid,Lot,EXP_DATE,MATR_SPEC from VIEW_SPD_STOCK_MAIN where rfid in ('" + String.join("','", actualRfids) + "') ";
        List<DeliveryOrderResult> orderResults = new ArrayList<>();
        try {
            ResultSet rs = executeQueryBySql(sql);
            while (rs.next()) {
                DeliveryOrderResult deliveryOrderResult = new DeliveryOrderResult();
                deliveryOrderResult.setStorageCode(rs.getString("WAREHOUSE_CODE"));
                deliveryOrderResult.setMaterialName(rs.getString("MATR_NAME"));
                deliveryOrderResult.setPy(PinYinUtils.getAlpha(rs.getString("MATR_NAME")) + rs.getString("rfid"));
                deliveryOrderResult.setRfid(rs.getString("rfid"));
                deliveryOrderResult.setLot(rs.getString("Lot"));
                deliveryOrderResult.setEXP(rs.getString("EXP_DATE"));
                deliveryOrderResult.setMaterialSpec(rs.getString("MATR_SPEC"));
                deliveryOrderResult.setAmount(1);
                orderResults.add(deliveryOrderResult);
                actualRfids.remove(deliveryOrderResult.getRfid());
            }
            sql = "select WAREHOUSE_CODE,MATR_NAME,rfid from VIEW_SPD_CONSUME where rfid in ('" + String.join("','", actualRfids) + "') and WAREHOUSE_CODE='" + stationCode + "'";
            ResultSet rsConsume = executeQueryBySql(sql);
            while (rsConsume.next()) {
                DeliveryOrderResult deliveryOrderResult = new DeliveryOrderResult();
                deliveryOrderResult.setStorageCode(rsConsume.getString("WAREHOUSE_CODE"));
                deliveryOrderResult.setMaterialName(rsConsume.getString("MATR_NAME") + "(已消耗)");
                deliveryOrderResult.setPy(PinYinUtils.getAlpha(rsConsume.getString("MATR_NAME")) + rsConsume.getString("rfid"));
                deliveryOrderResult.setRfid(rsConsume.getString("rfid"));
                deliveryOrderResult.setAmount(0);
                orderResults.add(deliveryOrderResult);
                actualRfids.remove(deliveryOrderResult.getRfid());
            }
            //处理无法识别的异常标签
            actualRfids.forEach(rfid -> {
                DeliveryOrderResult deliveryOrderResult = new DeliveryOrderResult();
                deliveryOrderResult.setStorageCode(stationCode);
                deliveryOrderResult.setOrderId("");
                deliveryOrderResult.setMaterialName("无效标签");
                deliveryOrderResult.setPy(PinYinUtils.getAlpha("无效标签") + rfid);
                deliveryOrderResult.setRfid(rfid);
                deliveryOrderResult.setAmount(0);
                orderResults.add(deliveryOrderResult);
            });
            switch (business) {
                case "OutboundOrder"://出库单补货
                    //获取所有出库单详情
                    rs = executeQueryBySql("select WAREHOUSE_CODE_TO,WO_KEY,MATR_NAME,rfid from VIEW_SPD_WO where WAREHOUSE_CODE_TO ='" + stationCode + "' and OP_FLAG = 'DOWN'");
                    List<DeliveryOrderResult> order = new ArrayList<>();
                    while (rs.next()) {
                        DeliveryOrderResult deliveryOrderResult = new DeliveryOrderResult();
                        deliveryOrderResult.setStorageCode(rs.getString("WAREHOUSE_CODE_TO"));
                        deliveryOrderResult.setOrderId(rs.getString("WO_KEY"));
                        deliveryOrderResult.setMaterialName(rs.getString("MATR_NAME"));
                        deliveryOrderResult.setPy(PinYinUtils.getAlpha(rs.getString("MATR_NAME")) + rs.getString("rfid"));
                        deliveryOrderResult.setRfid(rs.getString("rfid"));
                        deliveryOrderResult.setAmount(1);
                        order.add(deliveryOrderResult);
                    }
                    orderResults.forEach(o -> {
                        //配送的未入库时，库存试图不存在该耗材信息,只能去配送单试图关联
                        DeliveryOrderResult deliveryOrderResult = order.stream().filter(u -> u.getRfid().equals(o.getRfid())).findFirst().orElse(new DeliveryOrderResult());
                        if (deliveryOrderResult.getRfid() != null) {
                            o.setOrderId(deliveryOrderResult.getOrderId());//关联配送单号
                            o.setAmount(1);
                            o.setRfid(deliveryOrderResult.getRfid());
                            o.setMaterialName(deliveryOrderResult.getMaterialName());
                        }
                        List<Map<String, String>> desc = new ArrayList<>();
                        Map<String, String> item = new HashMap<>();
                        item.put("label", "品名");
                        item.put("value", o.getMaterialName());
                        desc.add(item);
                        item = new HashMap<>();
                        item.put("label", "单号");
                        item.put("value", deliveryOrderResult.getOrderId());
                        desc.add(item);
                        item = new HashMap<>();
                        item.put("label", "rfid");
                        item.put("value", o.getRfid());
                        desc.add(item);
                        o.setDesc(desc);
                    });
                    break;
                case "Delivery": // 耗材出库
                    orderResults.forEach(o -> {
                        List<Map<String, String>> desc = new ArrayList<>();
                        Map<String, String> item = new HashMap<>();
                        item.put("label", "品名");
                        item.put("value", o.getMaterialName());
                        desc.add(item);
                        item = new HashMap<>();
                        item.put("label", "品规");
                        item.put("value", o.getMaterialSpec() == null ? "-" : o.getMaterialSpec());
                        desc.add(item);
                        item = new HashMap<>();
                        item.put("label", "批号效期rfid");
                        item.put("value", (o.getLot() == null ? "-" : o.getLot()) + ";" + (o.getEXP() == null ? "-" : o.getEXP()) + ";" + o.getRfid());
                        desc.add(item);
                        o.setDesc(desc);
                    });
                    break;
            }
        } catch (Exception e) {
            return e.getMessage();
        }
        del.put("orderDet", orderResults);
        return del;
    }

    @Override
    public SPDResponseResult submit(String stationCode, String business, List<String> orderId) {
        SPDResponseResult spdResponseResult = new SPDResponseResult();
        JSONObject jsonObject = new JSONObject();
        UserPrincipal currentUser = UserUtils.currentUser();
        FsdUser fsdUser = fsdUserService.getById(currentUser.getId());
        jsonObject.put("orderid", orderId.toString());
        jsonObject.put("userid", fsdUser.getRelateId());

        FsdCallInterface fsdCallInterface = new FsdCallInterface();
        fsdCallInterface.setStationCode(stationCode);
        fsdCallInterface.setUserId(fsdUser.getId());
        fsdCallInterface.setInterfaceName("replenishmentSubmit");
        fsdCallInterface.setParameter(jsonObject.toString());
        fsdCallInterface.setSuccessful(false);
        if (fsdCallInterfaceService.save(fsdCallInterface)) {
            spdResponseResult.setCode(0);
            spdResponseResult.setMsg("记录补货成功");
            // 异步调用消耗接口
            ExecutorService newSingleThreadPool = Executors.newSingleThreadExecutor();
            newSingleThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    JSONObject resDel = JSONObject.parseObject(HaiYuSOAP.getDepotReceived(jsonObject.toString()));
                    System.out.println(resDel);
                    fsdCallInterface.setSuccessful(resDel.getInteger("code") == 0);
                    fsdCallInterface.setFirstResults(resDel.getString("msg"));
                    fsdCallInterfaceService.updateById(fsdCallInterface);
                }
            });
        } else {
            spdResponseResult.setCode(1);
            spdResponseResult.setMsg("补货失败");
        }
        return spdResponseResult;
    }

    @Override
    public SPDResponseResult deliverySubmit(String stationCode, String rfids) {
        SPDResponseResult spdResponseResult = new SPDResponseResult();
        JSONObject jsonObject = new JSONObject();
        UserPrincipal currentUser = UserUtils.currentUser();
        FsdUser fsdUser = fsdUserService.getById(currentUser.getId());
        jsonObject.put("userid", fsdUser.getRelateId());
        jsonObject.put("flag", "1");//消耗类型, (1消耗, -1 反消耗)
        jsonObject.put("depot_id", stationCode);
        jsonObject.put("case_nbr", rfids);
        FsdCallInterface fsdCallInterface = new FsdCallInterface();
        fsdCallInterface.setStationCode(stationCode);
        fsdCallInterface.setUserId(fsdUser.getId());
        fsdCallInterface.setInterfaceName("deliverySubmit");
        fsdCallInterface.setParameter(jsonObject.toString());
        fsdCallInterface.setSuccessful(false);
        if (fsdCallInterfaceService.save(fsdCallInterface)) {
            spdResponseResult.setCode(0);
            spdResponseResult.setMsg("记录消耗成功");
            // 异步调用消耗接口
            ExecutorService newSingleThreadPool = Executors.newSingleThreadExecutor();
            newSingleThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    JSONObject resDel = JSONObject.parseObject(HaiYuSOAP.getDepotHost(jsonObject.toString()));
                    System.out.println(resDel);
//        IFySpdWebService service = new IFySpdWebService();
//        JSONObject resDel = JSONObject.parseObject(service.getIFySpdWebServiceSOAP11PortHttp().getDepotHost(jsonObject.toString()));
                    fsdCallInterface.setSuccessful(resDel.getInteger("code") == 0);
                    fsdCallInterface.setFirstResults(resDel.getString("msg"));
                    fsdCallInterfaceService.updateById(fsdCallInterface);
                }
            });
        } else {
            spdResponseResult.setCode(1);
            spdResponseResult.setMsg("消耗失败");
        }
        return spdResponseResult;
    }

    @Override
    public List<Map<String, Object>> getMessageData(String stationCode) {
        List<Map<String, Object>> msgList = new ArrayList<>();
        Map<String, Object> del = new HashMap<>();
        List<Map<String, Object>> contList = new ArrayList<>();
        Map<String, Object> contDel;
        del.put("id", 10);
        del.put("title", "出库记录/日");
        del.put("isNew", false);
        List<Map> records = njglMapper.getRecordTodayByStationCode(stationCode);//recordService.getRecordByStationCode(stationCode);
        records = getDetailed(records,stationCode);
        for (Map rec : records) {
            if(rec.get("MaterialName").equals("无效标签")) continue;
            contDel = new HashMap<>();
            contDel.put("id", contList.size());
            contDel.put("msg", "" + rec.get("userName") + rec.get("type") + rec.get("MaterialName") + rec.get("rfid"));
            contDel.put("time", rec.get("changeTime"));
            contList.add(contDel);
        }
        del.put("content", contList);
        msgList.add(del);
        del = new HashMap<>();
        List<Map> recordWeek = njglMapper.getRecordWeekByStationCode(stationCode);
        recordWeek = getDetailed(recordWeek,stationCode);
        del.put("id", 20);
        del.put("title", "出库记录/周");
        del.put("isNew", false);
        contList = new ArrayList<>();
        //按品名分组统计
        Map<Object, Long> recordWeekMap = recordWeek.stream().filter(rw->!rw.get("MaterialName").equals("无效标签")).collect(Collectors.groupingBy(w ->w.get("MaterialName"),Collectors.counting()));
        for (Map.Entry<Object, Long> countMater : recordWeekMap.entrySet()) {
            contDel = new HashMap<>();
            contDel.put("id", contList.size() + 1);
            contDel.put("msg", countMater.getKey());
            contDel.put("time", countMater.getValue());
            contList.add(contDel);
        }
        del.put("content", contList);
        msgList.add(del);

        del = new HashMap<>();
        List<Map> recordMonth = njglMapper.getRecordMonthByStationCode(stationCode);
        recordMonth = getDetailed(recordMonth,stationCode);
        del.put("id", 30);
        del.put("title", "出库记录/月");
        del.put("isNew", false);
        contList = new ArrayList<>();
        Map<Object, Long> recordMonthMap = recordMonth.stream().filter(rw->!rw.get("MaterialName").equals("无效标签")).collect(Collectors.groupingBy(w ->w.get("MaterialName"),Collectors.counting()));
        for (Map.Entry<Object, Long> countMater : recordMonthMap.entrySet()) {
            contDel = new HashMap<>();
            contDel.put("id", contList.size() + 1);
            contDel.put("msg", countMater.getKey());
            contDel.put("time", countMater.getValue());
            contList.add(contDel);
        }
        del.put("content", contList);
        msgList.add(del);
        msgList.sort(Comparator.comparing(o -> o.get("id").toString()));
        return msgList;
    }

    @Override
    public Map<String, Object> getShortcutData(String stationCode) {
        JSONArray shortcut = JSONArray.parseArray(JSON.toJSONString(intelliAPIMapper.getShortcutData(stationCode)));
        Map<String, Object> res = new HashMap<>();
        Map subSheet = new HashMap();
        subSheet.put("subSheet1", shortcut.getJSONObject(1).getJSONArray("content").getJSONObject(0).getString("value"));//过效期
        subSheet.put("subSheet2", shortcut.getJSONObject(1).getJSONArray("content").getJSONObject(1).getString("value"));//近30天
        subSheet.put("subSheet3", shortcut.getJSONObject(1).getJSONArray("content").getJSONObject(2).getString("value"));//近60天
        res.put("sheet1", subSheet);//近效期统计

        subSheet = new HashMap();
        subSheet.put("subSheet1", shortcut.getJSONObject(0).getJSONArray("content").getJSONObject(0).getString("value"));//库存
        subSheet.put("subSheet2", shortcut.getJSONObject(0).getJSONArray("content").getJSONObject(1).getString("value"));//盘盈
        subSheet.put("subSheet3", shortcut.getJSONObject(0).getJSONArray("content").getJSONObject(2).getString("value"));//盘亏
        res.put("sheet2", subSheet);//库存统计

        subSheet = new HashMap();
        subSheet.put("subSheet1", shortcut.getJSONObject(2).getJSONArray("content").getJSONObject(0).getString("value"));//额定数量
        subSheet.put("subSheet2", shortcut.getJSONObject(2).getJSONArray("content").getJSONObject(1).getString("value"));
        subSheet.put("subSheet3", shortcut.getJSONObject(2).getJSONArray("content").getJSONObject(2).getString("value"));//差额数量
        res.put("sheet3", subSheet);//取出数量

        subSheet = new HashMap();
        subSheet.put("subSheet1", shortcut.getJSONObject(3).getJSONArray("content").getJSONObject(0).getString("value"));//当日消耗
        subSheet.put("subSheet2", shortcut.getJSONObject(3).getJSONArray("content").getJSONObject(1).getString("value"));//上日消耗
        subSheet.put("subSheet3", shortcut.getJSONObject(3).getJSONArray("content").getJSONObject(2).getString("value"));//前日消耗
        res.put("sheet4", subSheet);//消耗数量
        return res;
    }

    @Override
    public LoginResult getUserInfoByToken(String token) {
        UserPrincipal currentUser = UserUtils.currentUser();
        FsdUser fsdUser = fsdUserService.getById(currentUser.getId());
        List<Map<String, Object>> roles = new ArrayList<>();
        Map<String, Object> mouldStructure = new LinkedHashMap<>();
        //加入角色
        List<FsdRole> fsdRoles = fsdRoleService.listRoleByUserId(currentUser.getId());
        for (FsdRole role : fsdRoles) {
            Map<String, Object> ro = new HashMap<>();
            if (role.getRoleKey().equals("setting")) {
                ro.put("mouldName", "100");
                ro.put("iconLogo", FsdConst.iconCog);
            } else if (role.getRoleKey().equalsIgnoreCase("Operation_Preparation")) {
                ro.put("mouldName", "2");//需要在后台管理中添加这些配置
                ro.put("iconLogo", FsdConst.iconNotesMedical);
            } else if (role.getRoleKey().equalsIgnoreCase("OperatingRoom_Preparation")) {
                ro.put("mouldName", "2");
                ro.put("iconLogo", FsdConst.iconPrescriptionBottleAlt);
            } else if (role.getRoleKey().equalsIgnoreCase("stock")) {
                ro.put("mouldName", "3");
                ro.put("iconLogo", FsdConst.iconClipboardList);
            } else if (role.getRoleKey().equalsIgnoreCase("Report")) {
                ro.put("mouldName", "4");
                ro.put("iconLogo", FsdConst.iconFileSignature);
            } else if (role.getRoleKey().equalsIgnoreCase("DVR")) {
                ro.put("mouldName", "5");
                ro.put("iconLogo", FsdConst.iconFileVideo);
            } else if (role.getRoleKey().equalsIgnoreCase("Low_Consume")) {
                ro.put("mouldName", "1");
                ro.put("iconLogo", FsdConst.iconCoins);
            } else if (role.getRoleKey().equalsIgnoreCase("Operation_Return")) {
                ro.put("mouldName", "1");
                ro.put("iconLogo", FsdConst.iconDollyflatbed);
            } else if (role.getRoleKey().equalsIgnoreCase("Transfer")) {
                ro.put("mouldName", "1");
                ro.put("iconLogo", FsdConst.iconTruckLoading);
            } else if (role.getRoleKey().equalsIgnoreCase("Replenishment")) {
                ro.put("mouldName", "1");
                ro.put("iconLogo", FsdConst.iconBoxes);
            } else if (role.getRoleKey().equalsIgnoreCase("OutboundOrder")) {
                ro.put("mouldName", "OutboundOrder");
                ro.put("iconLogo", FsdConst.iconBoxes);
            } else if (role.getRoleKey().equalsIgnoreCase("Delivery")) {
                ro.put("mouldName", "Delivery");
                ro.put("iconLogo", FsdConst.iconTruckLoading);
            } else {
                ro.put("mouldName", "1");
                ro.put("iconLogo", FsdConst.iconBoxes);
            }
            ro.put("id", role.getSort());//role.getId());
            ro.put("iconName", role.getRoleName());
            ro.put("business", role.getRoleKey());
            roles.add(ro);
        }
        for (FsdRole role : fsdRoles) {
            mouldStructure.put(role.getRoleKey(), getMouldOne(role.getRoleKey()));
        }
        List<Map<String, Object>> sheetShortcut = new ArrayList<>();
        for (int i = 1; i < 5; i++) {
            Map<String, Object> shortcutItem = new HashMap<>();
            Map sheet = new HashMap();
            sheet.put("tab", "sheet" + i);
            sheet.put("title", i == 1 ? "近效期统计" : i == 2 ? "库存统计" : i == 3 ? "取出数量" : "消耗数量");
            shortcutItem.put("sheet", sheet);
            List<Map<String, String>> subSheet = new ArrayList<>();
            for (int j = 1; j < 4; j++) {
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.DATE, -j + 1);
                Map sub = new HashMap();
                sub.put("tab", "subSheet" + j);
                sub.put("title", i == 1 && j == 1 ? "过效期" : i == 1 && j == 2 ? "近30天" : i == 1 && j == 3 ? "近60天" : i == 2 && j == 1 ? "盘亏" : i == 2 && j == 2 ? "盘盈" : i == 2 && j == 3 ? "库存" : i == 3 && j == 1 ? DateUtils.format(new Date(), "dd") + "号取出" : i == 3 && j == 2 ? DateUtils.format(cal.getTime(), "dd") + "号取出" : i == 3 && j == 3 ? DateUtils.format(cal.getTime(), "dd") + "号取出" : i == 4 && j == 1 ? DateUtils.format(new Date(), "dd") + "号消耗" : i == 4 && j == 2 ? DateUtils.format(cal.getTime(), "dd") + "号消耗" : i == 4 && j == 3 ? DateUtils.format(cal.getTime(), "dd") + "号消耗" : "");
                subSheet.add(sub);
            }
            shortcutItem.put("subSheet", subSheet);
            sheetShortcut.add(shortcutItem);
        }
        mouldStructure.put("sheetShortcut", sheetShortcut);
        LoginResult loginResult = new LoginResult();
        loginResult.setUserId(fsdUser.getId());
        loginResult.setJobNumber(fsdUser.getJobNumber());
        loginResult.setCardId(fsdUser.getCardId());
        loginResult.setName(fsdUser.getUserName());
        loginResult.setJob(fsdUser.getJob());
        loginResult.setRoles(roles);
        loginResult.setMouldStructure(mouldStructure);
        return loginResult;
    }

    @Override
    public Object getStockData(String stationCode) {
        Map<String, Object> del = new HashMap<>();
        String sql = "select GOODS_OPCODE,MATR_NAME,MATR_SPEC,MATR_UNIT,WAREHOUSE_CODE,LOT,EXP_DATE,RFID from VIEW_SPD_STOCK_MAIN where WAREHOUSE_CODE= '" + stationCode + "'";
        //获取SPD库存视图中的理论库存
        List<StockResult> theoryStock = new ArrayList<>();
        try {
            ResultSet rs = executeQueryBySql(sql);
            Integer id = 1;
            while (rs.next()) {
                StockResult stockResult = new StockResult();
                stockResult.setId(id++);
                stockResult.setMaterialCode(rs.getString("GOODS_OPCODE"));
                stockResult.setMaterialName(rs.getString("MATR_NAME"));
                stockResult.setPy(PinYinUtils.getAlpha(stockResult.getMaterialName()));
                stockResult.setMaterialSpec(rs.getString("MATR_SPEC"));
                stockResult.setUnit(rs.getString("MATR_UNIT"));
//                stockResult.setType(rs.getString("Type"));
//                stockResult.setPackageUnit(rs.getString("PackageUnit"));
//                stockResult.setPackageQty(rs.getInt("PackageQty"));
                stockResult.setRfid(rs.getString("RFID"));
                stockResult.setLot(rs.getString("Lot"));
                stockResult.setExp(rs.getString("EXP_DATE"));
//                stockResult.setStockQty(rs.getInt("StockQty"));
//                stockResult.setLockQty(rs.getInt("LockQty"));
                stockResult.setStorageCode(rs.getString("WAREHOUSE_CODE")+"");
//                stockResult.setInactive(rs.getBoolean("Inactive"));
                List<Map<String, String>> desc = new ArrayList<>();
                Map<String, String> item = new HashMap<>();
                item.put("label", "品名");
                item.put("value", stockResult.getMaterialName());
                desc.add(item);
                item = new HashMap<>();
                item.put("label", "品规");
                item.put("value", stockResult.getMaterialSpec());
                desc.add(item);
                item = new HashMap<>();
                item.put("label", "批号效期");
                item.put("value", stockResult.getLot() + ";" + stockResult.getExp() + ";" + stockResult.getRfid());
                desc.add(item);
                stockResult.setDesc(desc);
                theoryStock.add(stockResult);
            }
        } catch (Exception e) {
            return e.getMessage();
        }
        del.put("stock", theoryStock);
        return del;
    }

    private List<ReportResult> getReport(String sql) {
        List<ReportResult> reportResultList = new ArrayList<>();
        try {
            ResultSet rs = executeQueryBySql(sql);
            System.out.println(sql);
            while (rs.next()) {
                ReportResult reportResult = new ReportResult();
                reportResult.setRfid(rs.getString("rfid"));
                reportResult.setMaterialName(isExistColumn(rs,"matr_name")?rs.getString("matr_name"):"无效标签");
                reportResult.setMaterialSpec(isExistColumn(rs,"matr_spec")?rs.getString("matr_spec"):"");
                reportResult.setLot(isExistColumn(rs,"Lot")?rs.getString("Lot"):"");
                reportResult.setExp(isExistColumn(rs,"exp_date")?rs.getString("exp_date"):"");
                reportResultList.add(reportResult);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reportResultList;
    }

    /**
     * 消耗接口调用
     * @return
     */
    public void autoCallInterface() {
        //接口调用失败且调用三次以内
        List<FsdCallInterface> fsdCallInterfaceList = fsdCallInterfaceService.list(Wrappers.<FsdCallInterface>query().eq("successful", false).isNull("third_results"));
        String result = "";
        JSONObject resDel = new JSONObject();
        for (FsdCallInterface fsdCallInterface : fsdCallInterfaceList) {
            switch (fsdCallInterface.getInterfaceName()) {
                case "deliverySubmit":
                    resDel = JSONObject.parseObject(HaiYuSOAP.getDepotHost(fsdCallInterface.getParameter()));
                    break;
                case "replenishmentSubmit":
                    resDel = JSONObject.parseObject(HaiYuSOAP.getDepotReceived(fsdCallInterface.getParameter()));
                    break;
            }
            fsdCallInterface.setSuccessful(resDel.getInteger("code") == 0);
            result = resDel.getString("msg");
             if (StringUtils.isBlank(fsdCallInterface.getSecondResults()))
                fsdCallInterface.setSecondResults(result);
            else if (StringUtils.isBlank(fsdCallInterface.getThirdResults()))
                fsdCallInterface.setThirdResults(result);
            fsdCallInterfaceService.updateById(fsdCallInterface);
        }
    }

    public Map<String, Object> getMouldOne(String business) {
        FsdRole role = fsdRoleService.getOne(new QueryWrapper<FsdRole>()
                .eq("role_key", business));
        if (role == null) throw new BusinessException("无效业务标识");
        Map<String, Object> item = new HashMap<>();

        Map<String, String> size = new HashMap<>();
        size.put("titleDiv", "10");//此处缺少后台配置
        size.put("listDiv", "85");
        size.put("bottomDiv", "5");
        item.put("size", size);

        Map<String, Object> titleCard = new HashMap<>();
        titleCard.put("title", role.getRoleName());
        item.put("titleCard", titleCard);

        Map<String, Object> list = new HashMap<>();
        Map<String, Object> listitem = new HashMap<>();
        Map<String, Object> action = new HashMap<>();

        if (role.getRoleKey().equalsIgnoreCase("stock")) {//库存统计
//            listitem.put("id", 3);
//            listitem.put("title", "盘亏");
//            action.put("isPicker", false);
//            listitem.put("action", action);
//            list.put("loss", listitem);
//
//            listitem = new HashMap<>();
//            action = new HashMap<>();
//            listitem.put("id", 2);
//            listitem.put("title", "盘盈");
//            action.put("isPicker", false);
//            listitem.put("action", action);
//            list.put("surplus", listitem);
//
//            listitem = new HashMap<>();
//            action = new HashMap<>();
            listitem.put("id", 1);
            listitem.put("title", "库存");
            action.put("isPicker", true);
            listitem.put("action", action);
            list.put("stock", listitem);

//            listitem = new HashMap<>();
//            action = new HashMap<>();
//            listitem.put("id", 4);
//            listitem.put("title", "存取记录");
//            action.put("isPicker", false);
//            listitem.put("action", action);
//            list.put("log", listitem);
            item.put("list", list);
            return item;
        }

        listitem.put("id", 1);
        listitem.put("title", "预操作耗材");
        action.put("isPicker", true);
        listitem.put("action", action);
        list.put("difMat", listitem);

        listitem = new HashMap<>();
        action = new HashMap<>();
        listitem.put("id", 2);
        listitem.put("title", "库存耗材");
        action.put("isPicker", false);
        listitem.put("action", action);
        list.put("unMat", listitem);
        item.put("list", list);

        Map<String, Object> button = new HashMap<>();
        button.put("iconLogo", FsdConst.iconCheckSquare);
        button.put("iconName", "确认");
        item.put("button1", button);

        if (role.getRoleKey().equalsIgnoreCase("Report")) {//报表模板
            item = new HashMap<>();
            List<Map<String, Object>> buttonList = new ArrayList<>();
            List<Object> allSheet = new ArrayList<>();
            for (int i = 1; i < 5; i++) {
                Map<String, Object> allSheetItem = new HashMap<>();
                button = new HashMap<>();
                button.put("iconLogo", FsdConst.iconClipboardList);
                button.put("iconName", i == 1 ? "库存统计" : i == 2 ? "近效期" : i == 3 ? "存取统计" : "消耗");
                button.put("sheetTab", "sheet" + i);
                buttonList.add(button);

                Map<String, String> sheetItem = new HashMap<>();
                sheetItem.put("tab", "sheet" + i);
                sheetItem.put("title", i == 1 ? "库存统计" : i == 2 ? "效期提醒" : i == 3 ? "存取统计" : "消耗明细");
                allSheetItem.put("sheet", sheetItem);
                List<Object> subSheet = new ArrayList<>();
                for (int j = 1; j < 4; j++) {
                    Calendar cal = Calendar.getInstance();
                    cal.add(Calendar.DATE, -j + 1);
                    Map<String, String> subSheetItem = new HashMap<>();
                    subSheetItem.put("tab", "subSheet" + j);
                    subSheetItem.put("title", i == 1 && j == 1 ? "盘亏" : i == 1 && j == 2 ? "盘盈" : i == 1 && j == 3 ? "库存" : i == 2 && j == 1 ? "过效期" : i == 2 && j == 2 ? "近30天" : i == 2 && j == 3 ? "近60天" : i == 3 && j == 1 ? DateUtils.format(new Date(), "dd") + "号存取" : i == 3 && j == 2 ? DateUtils.format(cal.getTime(), "dd") + "号存取" : i == 3 && j == 3 ? DateUtils.format(cal.getTime(), "dd") + "号存取" : i == 4 && j == 1 ? DateUtils.format(new Date(), "dd") + "号消耗" : i == 4 && j == 2 ? DateUtils.format(cal.getTime(), "dd") + "号消耗" : i == 4 && j == 3 ? DateUtils.format(cal.getTime(), "dd") + "号消耗" : "");
                    subSheet.add(subSheetItem);
                }
                allSheetItem.put("subSheet", subSheet);
                List<Object> matDesc = new ArrayList<>();
                Map<String, Object> matDescItem = new HashMap<>();
                if (i == 3) {
                    matDescItem.put("label", "用户");
                    Map<String, Object> search = new HashMap<>();
                    search.put("label", "用户或工号");
                    search.put("mode", "keyword");
                    search.put("addition", null);
                    matDescItem.put("search", search);
                    matDesc.add(matDescItem);
                    matDescItem = new HashMap<>();
                    matDescItem.put("label", "操作方式");
                    search = new HashMap<>();
                    search.put("label", "操作方式");
                    search.put("mode", "choice");
                    String[] choice = new String[]{"取出", "放入"};
                    search.put("addition", choice);
                    matDescItem.put("search", search);
                    matDesc.add(matDescItem);
                    matDescItem = new HashMap<>();
                    matDescItem.put("label", "耗材");
                    search = new HashMap<>();
                    search.put("label", "耗材");
                    search.put("mode", "keyword");
                    search.put("addition", null);
                    matDescItem.put("search", search);
                    matDesc.add(matDescItem);
                } else {
                    matDescItem.put("label", "品名");
                    Map<String, String> search = new HashMap<>();
                    search.put("label", "品名");
                    search.put("mode", "keyword");
                    search.put("addition", null);
                    matDescItem.put("search", search);
                    matDesc.add(matDescItem);
                    matDescItem = new HashMap<>();
                    matDescItem.put("label", "品规");
                    search = new HashMap<>();
                    search.put("label", "品规");
                    search.put("mode", "keyword");
                    search.put("addition", null);
                    matDescItem.put("search", search);
                    matDesc.add(matDescItem);
                    matDescItem = new HashMap<>();
                    matDescItem.put("label", "明细");
                    search = new HashMap<>();
                    search.put("label", "RFID");
                    search.put("mode", "keyword");
                    search.put("addition", null);
                    matDescItem.put("search", search);
                    matDesc.add(matDescItem);
                }
                allSheetItem.put("matDesc", matDesc);
                allSheet.add(allSheetItem);
            }
            item.put("button", buttonList);
            item.put("allSheet", allSheet);
            return item;
        }
        if (role.getRoleKey().equalsIgnoreCase("OutboundOrder") || role.getRoleKey().equalsIgnoreCase("Delivery")) { //出库单补货 / 耗材出库
            button = new HashMap<>();
            button.put("iconLogo", FsdConst.iconDollyflatbed);
            button.put("iconName", "开门");
            item.put("button2", button);
            list = new HashMap<>();
            listitem = new HashMap<>();
            action = new HashMap<>();
            listitem.put("id", 1);
            listitem.put("title", role.getRoleKey().equalsIgnoreCase("OutboundOrder") ? "配送单详情" : "出库单详情");
            action.put("isPicker", false);
            listitem.put("action", action);
            list.put("orderDet", listitem);
            item.put("list", list);
        }
        return item;
    }
    private List<Map> getDetailed(List<Map> records,String stationCode){
        List<String> rfids = records.stream().map(r -> r.get("rfid").toString()).collect(Collectors.toList());
        String sql = "select * from VIEW_SPD_STOCK_MAIN where rfid in ('" + String.join("','", rfids) + "') ";
        List<DeliveryOrderResult> orderResults = new ArrayList<>();
        try {
            ResultSet rs = executeQueryBySql(sql);
            while (rs.next()) {
                rs.getString("rfid");
                records.forEach(r -> {
                    for (Object value : r.values()) {
                        try {
                            if (value.toString().equals(rs.getString("rfid"))) {
                                r.put("MaterialName", rs.getString("MATR_NAME"));
                            }
                        } catch (SQLException throwables) {
                            throwables.printStackTrace();
                        }
                    }
                });
            }
            List<Map> notNames=records.stream().filter(r->r.get("MaterialName").equals("无效标签")).collect(Collectors.toList());
            List<String> notNameRfids= new ArrayList<>();
            for(Map notName : notNames){
                notNameRfids.add(notName.get("rfid").toString());
            }
            if(notNameRfids.size()>0) {
                sql = "select * from VIEW_SPD_CONSUME where WAREHOUSE_CODE='" + stationCode + "' and rfid in ('" + String.join("','", notNameRfids) + "') ";
                ResultSet rsConsume = executeQueryBySql(sql);
                while (rsConsume.next()) {
                    rsConsume.getString("rfid");
                    records.forEach(r -> {
                        for (Object value : r.values()) {
                            try {
                                if (value.toString().equals(rsConsume.getString("rfid"))) {
//                                    r.put("type", "消耗");
                                    r.put("MaterialName", rsConsume.getString("MATR_NAME"));
                                }
                            } catch (SQLException throwables) {
                                throwables.printStackTrace();
                            }
                        }
                    });
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return records;
    }

}
